﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.ByCode;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Entities
{
    /// <summary>
    /// Represents the category entity.
    /// </summary>
    /// <remarks><pre>
    /// The entity regarding the disclosure level.
    /// 
    /// + Entire
    ///  | - Attributes(of the Extended level)
    ///  + Extended
    ///   + Base
    ///    | - Parent(of the Primary level)
    ///    | - ItemCount
    ///    | - SupplierCount
    ///    | - Flags
    ///    | - UpdatedOn
    ///    | - CreatedOn
    ///    | - Translations(of the same level)
    ///    + Keys
    ///     + Primary
    ///      | - EntityID
    /// 
    /// Note: upper level includes lower level.
    /// </pre></remarks>
    public class CatalogCategoryEntity : AuditableEntity,
        IRelationHolder<LookupAttributeEntity>
    {
        #region Fields

        private CatalogCategoryEntity _parent;
        private ICollection<TCatalogCategoryEntity> _translations;
        private ICollection<CatalogItemEntity> _items;
        private ICollection<CatalogSupplierEntity> _suppliers;
        private ICollection<LookupAttributeEntity> _attributes;
        private ICollection<CatalogCategoryEntity> _childs;

        #endregion

        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public CatalogCategoryEntity()
        {
            _parent = null;
            _translations = new List<TCatalogCategoryEntity>();
            _items = new List<CatalogItemEntity>();
            _suppliers = new List<CatalogSupplierEntity>();
            _attributes = new List<LookupAttributeEntity>();
            _childs = new List<CatalogCategoryEntity>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the parent category identifier.
        /// </summary>
        public virtual int ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the parent category.
        /// </summary>
        public virtual CatalogCategoryEntity Parent
        {
            get
            {
                return ParentID == 0 ? null : _parent;
            }
            set
            {
                _parent = value;
                ParentID = value == null ? 0 : value.EntityID;
            }
        }

        /// <summary>
        /// Gets or sets the number of suppliers.
        /// </summary>
        public virtual int SupplierCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the number of items.
        /// </summary>
        public virtual int ItemCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public virtual CatalogCategoryFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Collections

        /// <summary>
        /// Gets or sets the child category collection.
        /// </summary>
        public virtual ICollection<CatalogCategoryEntity> Childs
        {
            get
            {
                return _childs;
            }
            set
            {
                _childs = value;
            }
        }

        /// <summary>
        /// Gets or sets the attribute collection.
        /// </summary>
        public virtual ICollection<LookupAttributeEntity> Attributes
        {
            get
            {
                return _attributes;
            }
            set
            {
                _attributes = value;
            }
        }

        /// <summary>
        /// Gets or sets the supplier collection.
        /// </summary>
        public virtual ICollection<CatalogSupplierEntity> Suppliers
        {
            get
            {
                return _suppliers;
            }
            set
            {
                _suppliers = value;
            }
        }

        /// <summary>
        /// Gets or sets the item collection.
        /// </summary>
        public virtual ICollection<CatalogItemEntity> Items
        {
            get
            {
                return _items;
            }
            set
            {
                _items = value;
            }
        }

        /// <summary>
        /// Gets or sets the category translations.
        /// </summary>
        public virtual ICollection<TCatalogCategoryEntity> Translations
        {
            get
            {
                return _translations;
            }
            set
            {
                _translations = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the category translation.
        /// </summary>
        /// <param name="languageID">The language identifier.</param>
        /// <returns>The category translation.</returns>
        public virtual TCatalogCategoryEntity Translation(int languageID)
        {
            return _translations.SingleOrDefault(x => x.Language.EntityID == languageID);
        }

        public virtual void Map(LookupAttributeEntity child)
        {
            if(Attributes.Contains(child))
                return;
            Attributes.Add(child);
        }

        public virtual void Unmap(LookupAttributeEntity child)
        {
            if(!Attributes.Contains(child))
                return;
            Attributes.Remove(child);
        }

        #endregion

        #region Utilities

        protected override void Disclose(IDictionary<String, Object> obj,
            DisclosureLevel level,
            IDictionary<String, String> options)
        {
            base.Disclose(obj, level, options);
            if(level >= DisclosureLevel.Base)
            {
                obj["Parent"] = Parent != null 
                    ? Parent.Disclose(DisclosureLevel.Primary, options) 
                    : null;
                obj["ItemCount"] = ItemCount;
                obj["SupplierCount"] = SupplierCount;
                obj["Flags"] = Flags.ToString();
                obj["Translations"] = (options.ContainsKey("TranslatedTo")
                    ? Translations.Where(x => options["TranslatedTo"].Contains(x.Language.Code))
                    : Translations)
                    .Map(x => x.Disclose(level, options));
            }
            if(level >= DisclosureLevel.Entire)
                obj["Attributes"] = Attributes.Map(x => x.Disclose(DisclosureLevel.Extended, options));
        }

        #endregion
    }

    /// <summary>
    /// The entity NHibernate mapping.
    /// </summary>
    public class CatalogCategoryMapping : EntityMapping<CatalogCategoryEntity>
    {
        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public CatalogCategoryMapping()
        {
            Table("fwk_CatalogCategories");
            Id(x => x.EntityID, m =>
            {
                m.Column("CategoryID");
                m.Generator(Generators.Identity);
            });
            Property(x => x.ParentID, m =>
            {
                m.Column("ParentCategoryID");
                m.NotNullable(true);
            });
            ManyToOne(x => x.Parent, m =>
            {
                m.Column("ParentCategoryID");
                m.NotFound(NotFoundMode.Ignore);
                m.Insert(false);
                m.Update(false);
            });
            Property(x => x.SupplierCount, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.ItemCount, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.Flags, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CreatedOn, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.UpdatedOn, m =>
            {
                m.NotNullable(true);
            });
            Bag(x => x.Childs, m =>
            {
                m.Table("fwk_CatalogCategories");
                m.Key(k =>
                {
                    k.Column("ParentCategoryID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
                m.BatchSize(10);
            },
            a =>
            {
                a.OneToMany();
            });
            Bag(x => x.Attributes, m =>
            {
                m.Table("fwk_MCatalogCategoryAttributes");
                m.Key(k =>
                {
                    k.Column("CategoryID");
                    k.ForeignKey("FK_fwk_MCatalogCategoryAttributes_fwk_CatalogCategories");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("AttributeID");
                    m.ForeignKey("FK_fwk_MCatalogCategoryAttributes_fwk_LookupAttributes");
                });
            });
            Bag(x => x.Suppliers, m =>
            {
                m.Table("fwk_MCatalogSupplierCategories");
                m.Key(k =>
                {
                    k.Column("CategoryID");
                    k.ForeignKey("FK_fwk_MCatalogSupplierCategories_fwk_CatalogCategories");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("SupplierID");
                    m.ForeignKey("FK_fwk_MCatalogSupplierCategories_fwk_CatalogSuppliers");
                });
            });
            Bag(x => x.Items, m =>
            {
                m.Table("fwk_MCatalogItemCategories");
                m.Key(k =>
                {
                    k.Column("CategoryID");
                    k.ForeignKey("FK_fwk_MCatalogItemCategories_fwk_CatalogCategories");
                    k.NotNullable(true);
                });
                m.Inverse(true);
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("ItemID");
                    m.ForeignKey("FK_fwk_MCatalogItemCategories_fwk_CatalogItems");
                });
            });
            Bag(x => x.Translations, m =>
            {
                m.Table("fwk_TCatalogCategories");
                m.Key(k =>
                {
                    k.Column("CategoryID");
                    k.ForeignKey("FK_fwk_TCatalogCategories_fwk_CatalogCategories");
                    k.NotNullable(true);
                });
                m.Inverse(true);
                m.BatchSize(10);
            },
            a =>
            {
                a.OneToMany();
            });
            Cache(m =>
            {
                m.Usage(CacheUsage.ReadWrite);
            });
        }
    }
}
